<template>
  <div class="container">
    <h1>图书管理系统 📚</h1>
    <nav>
      <router-link to="/">🏠 首页</router-link>
      <router-link to="/locations/add">➕ 添加位置</router-link>
    </nav>
    <router-view/>
    <!-- 新增位置选择组件 -->
    <div class="location-selector-wrapper">
      <p>图书位置：</p>
      <LocationSelector v-model="selectedLocation" />
    </div>

    <!-- 扫码输入框 -->
    <div class="scanner-box">
      <input 
        ref="isbnInput"
        v-model="isbn"
        @keyup.enter="handleScan"
        placeholder="请使用扫码枪扫描ISBN"
        class="scan-input"
      >
      <button @click="handleScan">手动添加</button>
    </div>

    <!-- 搜索框 -->
    <input
      v-model="searchQuery"
      @input="searchBooks"
      placeholder="搜索图书..."
      class="search-input"
    >

    <!--
    图书列表 
    <BookList :books="books" @show-detail="showDetail" />
    -->

    <!-- 更新BookList组件绑定 -->
    <BookList 
      :books="books" 
      @show-detail="showDetail"
      @book-deleted="handleBookDeleted"
    />
    <!-- 详情弹窗 -->
    <div v-if="selectedBook" class="modal">
      <div class="modal-content">
        <h3>{{ selectedBook.title }}</h3>
        <p>ISBN: {{ selectedBook.isbn }}</p>
        <p>作者: {{ selectedBook.authors }}</p>
        <p>出版社: {{ selectedBook.publisher }}</p>
        <p>价格: {{ selectedBook.price }}</p>
        <div class="summary">{{ selectedBook.summary }}</div>
        <button @click="selectedBook = null">关闭</button>
      </div>
    </div>
  </div>
</template>

<script>
import LocationSelector from './components/LocationSelector.vue'
import BookList from './components/BookList.vue'
import { ref, onMounted, getCurrentInstance} from 'vue'

export default {
  components: { 
    BookList,
    LocationSelector
   },
  setup() {
    const { proxy } = getCurrentInstance()
    // 新增位置代码
    const selectedLocation = ref(null)

    const isbn = ref('')
    const searchQuery = ref('')
    const books = ref([])
    const selectedBook = ref(null)
    const isbnInput = ref(null)
    
    const error = ref(null)

    // 显示已有图书，并自动聚焦输入框
    onMounted(() => {
      fetchBooks()
      isbnInput.value.focus()
    })

    const fetchBooks = async (query = '') => {
      try {
        const res = await proxy.$api.get('/books',{
          params: {search: query }
        })
        books.value =  res.data
      } catch (err) {
        console.error('获取图书失败:', err)
      }
    }

    const handleScan = async () => {
      
      if (selectedLocation.value==null|selectedLocation.value=="") {
        showToast("请选择图书位置！","提示")
        return
      }
      if (!isbn.value.trim()) {
        showToast("请输入图书的ISBN号码！","提示")
        isbnInput.value.focus()
        return
      }
      
      try {
        const response = await proxy.$api.post('/books', 
          {
            isbn: isbn.value,
            location_code: selectedLocation.value 
          }
        )
        //清空输入
        isbn.value = ''
        isbnInput.value.focus()
        //默认不清空位置选择
        //selectedLocation.value = null

        fetchBooks()
        alert('图书添加成功！')
        return
      } catch (err) {
        handleApiError(err, '添加图书失败')
        //清空输入
        isbn.value = ''
        isbnInput.value.focus()
      }
    }

    // 统一错误处理
    const handleApiError = (err, defaultMsg) => {
      error.value = err.response?.data?.error || err.message || defaultMsg
      showToast(error.value, 'error')
      //console.error('API Error:', err)
    }

    // 显示通知
    const showToast = (message, type = 'info') => {
      // 这里可以集成第三方通知库如Toastification
      alert(`${type.toUpperCase()}: ${message}`)
    }

    const searchBooks = () => {
      fetchBooks(searchQuery.value)
    }

    const showDetail = (book) => {
      selectedBook.value = book
    }

    // 在setup函数中添加删除处理逻辑
    const handleBookDeleted = (deletedId) => {
      books.value = books.value.filter(book => book.id !== deletedId)
      if (selectedBook.value?.id === deletedId) {
        selectedBook.value = null
      }
    }

    return {
      selectedLocation,
      isbn,
      searchQuery,
      books,
      selectedBook,
      isbnInput,
      handleScan,
      searchBooks,
      showDetail,
      fetchBooks,
      handleBookDeleted
    }
  }
}
</script>

<style scoped>
.scanner-box {
  margin: 20px 0;
  display: flex;
  gap: 10px;
}

.scan-input {
  width: 300px;
  padding: 12px;
  font-size: 16px;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-content {
  background: white;
  padding: 30px;
  border-radius: 8px;
  max-width: 600px;
  max-height: 80vh;
  overflow-y: auto;
}

.summary {
  margin: 15px 0;
  line-height: 1.6;
  color: #666;
}

/* location-selector相关的新增样式 */
.location-selector-wrapper {
  margin: 15px 0;
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 15px;
}

.location-selector-wrapper h3 {
  margin: 0 0 10px 0;
  color: #666;
  font-size: 0.95em;
}

.scanner-box {
  margin-top: 20px;
}


nav {
  padding: 20px;
  background: #f8f9fa;
  margin-bottom: 20px;
}

nav a {
  margin-right: 15px;
  color: #2c3e50;
  text-decoration: none;
}

nav a.router-link-exact-active {
  color: #42b983;
  font-weight: bold;
}

</style>